<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
        <div class="common-layout">
            <el-container>
                <el-main>
                    <el-row>
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple">
                                <h4>基本信息</h4>
                                <el-form :inline="true" :model="purchaseInvoices" :rules="rules" status-icon
                                         ref="formRef">
                                    <el-form-item label="单据编号" prop="code">
                                        <el-input
                                            v-model="purchaseInvoices.code"
                                            style="width: 240px"
                                            placeholder="请输入单据编号"
                                            clearable
                                            :disabled="true"
                                        />
                                    </el-form-item>
                                    <!-- 供应商 -->
                                    <el-form-item label="供应商" prop="supplierId">
                                        <el-select
                                            v-model="purchaseInvoices.supplierId"
                                            placeholder="请选择供应商"
                                            style="width: 240px"
                                            clearable
                                            filterable
                                        >
                                            <el-option
                                                v-for="supplier in supplierList"
                                                :key="supplier.id"
                                                :label="`${supplier.code} - ${supplier.name}`"
                                                :value="supplier.id"
                                            />
                                        </el-select>
                                    </el-form-item>
                                    <!-- 单据日期 -->
                                    <el-form-item label="单据日期" prop="codeDate">
                                        <el-date-picker
                                            v-model="purchaseInvoices.codeDate"
                                            type="date"
                                            placeholder="请选择日期"
                                            value-format="YYYY-MM-DD"
                                            :disabled-date="disabledDate"
                                        />
                                    </el-form-item>
                                    <!-- 发票号 -->
                                    <el-form-item label="发票号" prop="invoiceNum">
                                        <el-input
                                            v-model="purchaseInvoices.invoiceNum"
                                            style="width: 240px"
                                            placeholder="请输入发票号"
                                        />
                                    </el-form-item>
                                </el-form>
                            </div>
                        </el-col>
                    </el-row>
                </el-main>
            </el-container>
        </div>
    </div>
    <div>
        <div class="toolbar">
            <el-button type="primary">商品信息</el-button>
            <el-button @click="addGoodsRow">继续添加</el-button>
            <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
        </div>
        <!-- 商品信息表格 -->
        <el-table :data="tableData" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column label="商品编码" width="150">
                <template #header>
                    <span class="required-label">商品编码</span>
                </template>
                <template #default="scope">
                    <el-select
                        v-model="scope.row.goodsCode"
                        placeholder="请选择商品"
                        @change="handleGoodsChange(scope.row)"
                        clearable
                    >
                        <el-option
                            v-for="item in goodsList"
                            :key="item.code"
                            :label="`${item.code} - ${item.name}`"
                            :value="item.code"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="商品名称" width="180">
                <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
            </el-table-column>
            <!-- 单位（带必填标识） -->
            <el-table-column label="单位" width="80" align="center">
                <template #header>
                    <span class="required-label">单位</span>
                </template>
                <template #default="scope">{{ scope.row.unit || '' }}</template>
            </el-table-column>
            <el-table-column label="仓库" width="150">
                <template #header>
                    <span class="required-label">仓库</span>
                </template>
                <template #default="scope">
                    <el-select
                        @change="storeChange(scope.row)"
                        v-model="scope.row.storeId"
                        placeholder="请选择仓库"
                        clearable
                    >
                        <el-option
                            v-for="store in storeList"
                            :key="store.id"
                            :label="`${store.code} - ${store.name}`"
                            :value="store.id"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="开票数量" width="130" align="center">
                <template #header>
                    <span class="required-label">开票数量</span>
                </template>
                <template #default="scope">
                    <el-input
                        v-model.number="scope.row.invoicingQuantity"
                        placeholder="输入数量"
                        @input="validatePrice(scope.row, 'invoicingQuantity')"
                    />
                </template>
            </el-table-column>
            <el-table-column label="开票金额" width="120" align="center">
                <template #header>
                    <span class="required-label">开票金额</span>
                </template>
                <template #default="scope">
                    <el-input
                        v-model.number="scope.row.invoicingAmount"
                        placeholder="输入金额"
                        @input="validatePrice(scope.row, 'invoicingAmount')"
                    >
                        <template #append>元</template>
                    </el-input>
                </template>
            </el-table-column>
            <el-table-column
                v-for="col in readonlyColumns"
                :key="col.prop"
                :prop="col.prop"
                :label="col.label"
                :width="col.width"
                align="center"
            />
        </el-table>
    </div>
    <div class="total-summary">
        <div class="total-label">合计</div>
        <div class="total-amount">{{ formatTotal }}</div>
    </div>
    <el-dialog
        v-model="dialogVisible"
        title="采购入库单"
        width="80%"
        top="5vh"
    >
        <div class="dialog-header">
            <el-input
                v-model="searchForm.docCode"
                placeholder="请输入单据编号"
                style="width: 240px;margin-right: 15px"
            />
            <span class="date-label">单据日期：</span>
            <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                style="width: 160px"
            />
            <span class="date-separator">~</span>
            <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 160px;margin-right: 15px"
            />
            <el-button type="primary" icon="Search" @click="searchPurchaseReceipts">查询</el-button>
            <el-button icon="Refresh" @click="resetSearch">重置</el-button>
            <el-button icon="ArrowDown">展开</el-button>
        </div>
        <div class="selected-info">
            <span>已选择{{ selectedCount }}项</span>
            <el-button link type="primary" @click="clearSelection">清空</el-button>
        </div>
        <el-table
            :data="purchaseReceiptList"
            border
            height="60vh"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column prop="code" label="单据编号" width="180"/>
            <el-table-column prop="orderDate" label="单据日期" width="120"/>
            <el-table-column prop="providerName" label="供应商" width="120"/>
            <el-table-column prop="deptName" label="业务部门" width="120"/>
            <el-table-column prop="businessmanName" label="业务员" width="120"/>
            <el-table-column prop="orderStatus" label="已关闭" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.orderStatus === 1 ? 'danger' : 'success'" size="small">
                        {{ scope.row.orderStatus === 1 ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>
        <div class="dialog-footer">
            <div class="pagination-wrapper">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :total="totalItems"
                    :page-size="PopupsPageSize"
                    :current-page="PopupsPageNo"
                    @current-change="handlePageChange"
                />
            </div>
            <div class="action-buttons">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="confirmSelection">确定</el-button>
            </div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, computed, onMounted, watch} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router';
import type {FormInstance} from 'element-plus';
import type {PublicProvider} from "@/types/public-cg/provider.ts";
import type {Goods} from "@/types/public-xs/Goods.ts";
import {
    CodeState,
    InvoiceType,
    type PurchaseInvoice,
    type PurchaseInvoiceDetail
} from "@/types/public-xs/PurchaseInvoice.ts";
import request from "@/util/request.ts";
import type {Store} from "@/types/basic/store.ts";

// 基本变量
const docCode = ref('');
const sourceSheet = ref('');
const title = ref('新增采购发票');
const goodsList = ref<Goods[]>([]);
const supplierList = ref<PublicProvider[]>([]);
const purchaseReceiptList = ref<PurchaseInvoice[]>([]);
const pageNo = ref(1);
const pageSize = ref(5);
const allPage = ref(0);
const router = useRouter();
const loading = ref(false); // 加载状态

// 仓库数据
const storeList = ref<Store[]>([]);
const selectStore = async () => {
    try {
        const response = await request.post('/basic/store/getAllStore');
        storeList.value = response.data.data || [];
    } catch (error) {
        ElMessage.error('获取仓库数据失败');
        console.error('获取仓库失败:', error);
    }
};
selectStore()

// 表单数据
const purchaseInvoices = ref<PurchaseInvoice>({
    id: 0,
    code: '',
    codeDate: '',
    invoiceType: InvoiceType.Normal,
    supplierId: null,
    invoiceNum: '',
    codeState: CodeState.NotAudited,
    originalOrderNum: '',
    amount: 0,
    orderCreationTime: new Date(),
    orderCreator: '当前用户',
    orderDepartment: '采购部',
    modifyTime: new Date(),
    modifier: '当前用户',
    isDelete: 0
});

// 生成 UUID
const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
};

// 商品表格数据
const tableData = ref([
    {
        id: generateUUID(),
        goodId: 0,
        goodsCode: '',
        goodsName: '',
        warehouseName: '',
        quantity: 0,
        invoicingQuantity: 0,
        invoicingAmount: 0,
        actualPrice: 0,
        storeId: null,
        tax: 0,
        taxIncludedPrice: 0,
        notes: '',
        unit: '',
        kname: '',
    },
]);

// 只读列
const readonlyColumns = [
    { prop: 'kname', label: '商品种类', width: 120 },
    // { prop: 'suggestedPrice', label: '建议报价', width: 120 },
    // { prop: 'taxIncludedPrice', label: '含税单价', width: 120 },
    { prop: 'tax', label: '增值税税率 (%)', width: 150 },
];

// 表单验证规则
const rules = reactive({
    supplierId: [{required: true, message: '请选择供应商', trigger: 'blur', type: 'number'}],
    code: [{required: true, message: '请输入单据编号', trigger: 'blur'}],
    codeDate: [{required: true, message: '请选择单据日期', trigger: 'change,blur'}],
    invoiceNum: [{required: true, message: '请输入发票号', trigger: 'blur'}],
});

const disabledDate = (time: Date) => {
    return time.getTime() > Date.now();
};

// 顶部按钮配置
const mainActions = ref([
    {name: 'save', label: '保存', type: 'primary', icon: 'DocumentAdd'},
    {name: 'save-add', label: '保存新增', disabled: false},
    {name: 'audit', label: '审核', hidden: false},
    {name: 'choose', label: '选择源单', hidden: false},
    {name: 'history', label: '历史单据', badge: 3},
]);

// 处理顶部按钮动作
const handleAction = (action: string) => {
    switch (action) {
        case 'choose':
            if (!purchaseInvoices.value.supplierId) {
                ElMessage.warning('请先选择供应商');
                return;
            }
            dialogVisible.value = true;
            break;
        case 'save-add':
            insertPurchaseInvoice();
            break;
        case 'history':
            router.push('/home/PurchaseOrderInfo');
            break;
    }
};

// 获取单据编号
const getDocCode = async () => {
    const response = await request.post('/xs/counter/addCode', {docType: 'CGFP'});
    docCode.value = response.data.data;
    purchaseInvoices.value.code = docCode.value;
};

// 获取供应商
const selectSupplier = async () => {
    try {
        loading.value = true;
        const response = await request.post('/basic/Provider/selectAllSupplier', {
            pageNo: 1,
            pageSize: 100,
        });
        if (response.data.code !== '200') {
            throw new Error(response.data.msg || '获取供应商失败');
        }
        supplierList.value = response.data.data || [];
    } catch (error) {
        ElMessage.error('获取供应商失败');
        console.error('获取供应商失败:', error);
    } finally {
        loading.value = false;
    }
};

// 商品查询条件
const queryConditions = reactive({
    combine: '',
    kid: '',
});

// 获取商品数据
const fetchData = async (page: number) => {
    try {
        loading.value = true;
        const params = new URLSearchParams();
        params.append('pageNow', page.toString());
        params.append('pageSize', pageSize.value.toString());
        params.append('combine', queryConditions.combine);
        params.append('kid', queryConditions.kid);

        const response = await request.post('/basic/good/getGoodPage', params, {
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        });

        console.log('getGoodPage 响应:', response.data);

        if (response.data.code !== '200' || !response.data.data || !Array.isArray(response.data.data.list)) {
            throw new Error(response.data.msg || '商品数据格式错误或为空');
        }

        goodsList.value = response.data.data.list.map((item) => ({
            id: item.id,
            code: item.code,
            name: item.name,
            unique: item.unique || '件',
            tax: item.tax || 13,
            stock: item.stock || 100,
            kname: item.kname || '',
            specification: item.specification || '默认规格',
        }));
        allPage.value = response.data.data.total || 0;
    } catch (error) {
        ElMessage.error('获取商品数据失败');
        goodsList.value = [];
        allPage.value = 0;
        console.error('获取商品数据失败:', error);
    } finally {
        loading.value = false;
    }
};

// 获取采购入库单
const selectPurchaseReceiptBySid = async () => {
    try {
        loading.value = true;
        console.log(purchaseInvoices.value)
        const params = {
            pageNo: PopupsPageNo.value,
            pageSize: PopupsPageSize.value,
            pid: purchaseInvoices.value.supplierId,
            typeId: 5
        };
        const response = await request.post('/kc/inStore/getInStoreList', params);
        purchaseReceiptList.value = response.data.data.list || [];
        console.log(purchaseReceiptList.value)
        totalItems.value = purchaseReceiptList.value.length;
    } catch (error) {
        ElMessage.error('获取采购入库单失败');
        purchaseReceiptList.value = [];
        totalItems.value = 0;
        console.error('获取采购入库单失败:', error);
    } finally {
        loading.value = false;
    }
};

// 监听供应商选择变化
watch(
    () => purchaseInvoices.value.supplierId,
    async (newSupplierId) => {
        if (newSupplierId) {
            await selectPurchaseReceiptBySid(newSupplierId);
        } else {
            purchaseReceiptList.value = [];
            totalItems.value = 0;
        }
    }
);



// 处理商品选择
const handleGoodsChange = (row: any) => {
    const selected = goodsList.value.find((item) => item.code === row.goodsCode);
    if (selected) {
        row.goodsName = selected.name;
        row.goodId = selected.id;
        row.specification = selected.type || '默认规格';
        row.unit = selected.uname || '件';
        row.taxRate = selected.tax || 13;
        row.kname = selected.kname || '';
        row.stock = selected.stock || 100;
        row.quantity = Math.max(1, Math.min(selected.stock || 1, row.quantity));
    } else {
        row.goodsName = '';
        row.specification = '';
        row.unit = '件';
        row.taxRate = 13;
        row.stock = 100;
        row.quantity = 1;
        row.kname = '';
    }
};

// 处理表格选中行
const newSelectedRows = ref<any[]>([]);
const newHHandleSelectionChange = (selection: any[]) => {
    newSelectedRows.value = selection;
};

// 删除选中行
const deleteSelectedRows = async () => {
    if (newSelectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的行');
        return;
    }
    try {
        await ElMessageBox.confirm(`确定要删除选中的 ${newSelectedRows.value.length} 行吗？`, '删除确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const selectedIds = new Set(newSelectedRows.value.map((row) => row.id));
        tableData.value = tableData.value.filter((row) => !selectedIds.has(row.id));
        ElMessage.success('删除成功');
    } catch (error) {
        ElMessage.info('已取消删除');
    }
};

// 价格校验
const validatePrice = (row: any) => {
    row.actualPrice = row.actualPrice.toString().replace(/[^\d.]/g, '');
    if (row.actualPrice) {
        row.actualPrice = parseFloat(row.actualPrice) || 0;
    }
};

// 计算单行开票金额
const calculateAmount = (row: any) => {
    const quantity = Number(row.quantity) || 0;
    const price = Number(row.actualPrice) || 0;
    return `¥${(quantity * price).toFixed(2)}`;
};

// 计算总金额
const totalAmount = computed(() => {
    return tableData.value.reduce((sum, row) => {
        const quantity = Number(row.invoicingQuantity) || 0;
        const price = Number(row.invoicingAmount) || 0;
        return sum + quantity * price;
    }, 0);
});

const formatTotal = computed(() => {
    return `¥${totalAmount.value.toFixed(2)}`;
});

// 弹窗相关
const PopupsPageNo = ref(1);
const PopupsPageSize = ref(10);
const selectedCount = ref(0);
const totalItems = ref(0);
const dialogVisible = ref(false);
const currentSelected = ref<PurchaseInvoice | null>(null);
const selectedRows = ref<PurchaseInvoice[]>([]);
const searchForm = reactive({
    docCode: '',
    startDate: '',
    endDate: '',
});

// 表格选择处理
const handleSelectionChange = (selection: PurchaseInvoice[]) => {
    selectedRows.value = selection;
    selectedCount.value = selection.length;
    currentSelected.value = selection.length > 0 ? selection[0] : null;
};

// 清空选择
const clearSelection = () => {
    selectedRows.value = [];
    selectedCount.value = 0;
    currentSelected.value = null;
};

// 分页处理
const handlePageChange = async (newPage: number) => {
    PopupsPageNo.value = newPage;
    await searchPurchaseReceipts();
};

// 搜索采购入库单
const searchPurchaseReceipts = async () => {
    try {
        loading.value = true;
        const params = {
            code: searchForm.docCode,
            pageNo: PopupsPageNo.value,
            pageSize: PopupsPageSize.value,
            startDate: searchForm.startDate,
            endDate: searchForm.endDate,
            pid: purchaseInvoices.value.supplierId,
            typeId: 5
        };
        const res = await request.post('/kc/inStore/getInStoreList', params);

        purchaseReceiptList.value = res.data.data.list || [];
        console.log(purchaseReceiptList.value)
        totalItems.value = res.data.data.total || 0;
    } catch (error) {
        ElMessage.error('查询采购入库单失败');
        console.error('查询失败:', error);
    } finally {
        loading.value = false;
    }
};


// 重置搜索
const resetSearch = () => {
    searchForm.docCode = '';
    searchForm.startDate = '';
    searchForm.endDate = '';
    searchPurchaseReceipts();
};

// 采购入库单明细类型
interface PurchaseInstoreDetail {
    id: number;
    instoreCode: string;
    goodsId: number;
    count: number;
    notes: string;
    storeId: number;
    taxsumPrice: number;
    sumPrice: number;
    createId: number;
    createDate: string;
    updateId: number;
    updateDate: string;
}

// 确认选择
const confirmSelection = async () => {
    if (!currentSelected.value) {
        ElMessage.warning('请先选择一个采购入库单');
        return;
    }
    const doCode = currentSelected.value.code;
    sourceSheet.value = doCode;
    purchaseInvoices.value.originalOrderNum = doCode;
    ElMessage.success(`已选择源单：${doCode}`);

    try {
        loading.value = true;
        // 获取采购入库单明细
        const detailRes = await request.get(
            `/cg/purchaseInvoice/selectPurchaseInstoreDetailByInstoreCode?instoreCode=${doCode}`
        );
        if (detailRes.data.code !== '200' || !Array.isArray(detailRes.data.data)) {
            throw new Error(detailRes.data.msg || '获取采购入库明细失败');
        }

        const details = detailRes.data.data;

        // 获取商品 ID
        const goodIds = details
            .map((item) => item.goodsId)
            .filter((id) => id > 0);

        // 查询商品信息
        let goodsMap = new Map<number, Goods>();
        if (goodIds.length > 0) {
            const goodsRes = await request.post('/basic/good/getGoodList', goodIds);
            if (goodsRes.data.code !== '200' || !Array.isArray(goodsRes.data.data)) {
                throw new Error(goodsRes.data.msg || '获取商品信息失败');
            }
            goodsRes.data.data.forEach((good) => {
                goodsMap.set(good.id, good);
            });
        }

        // 更新商品表格
        tableData.value = details.map((item) => {

            console.log(item)

            const good = goodsMap.get(item.goodsId) || {} as Goods;
            const actualPrice = item.invoicingQuantity > 0 ? item.invoicingAmount / item.invoicingQuantity : 0;
            return {
                id: generateUUID(),
                goodId: item.goodsId,
                goodsCode: good.code || '未知编码',
                goodsName: good.name || '未知商品',
                invoicingQuantity: item.invoicingQuantity,
                invoicingAmount: item.invoicingAmount,
                unit: good.uname || '件',
                quantity: item.count || 1,
                tax: item.tax,
                actualPrice: Number(actualPrice.toFixed(2)),
                kname: good.kname || '-',
                storeId:item.storeId,
                warehouseName: item.warehouseName,
            };
        });

        // 更新 purchaseInvoices 字段
        purchaseInvoices.value.orderCreator = '当前用户'; // API 未提供 createUser
        purchaseInvoices.value.orderDepartment = '采购部'; // API 未提供 did
    } catch (error: any) {
        ElMessage.error(error.message || '加载明细数据失败');
        console.error('加载明细失败:', error);
    } finally {
        loading.value = false;
        dialogVisible.value = false;
    }
};

// 生成发票明细
const generateDetails = (): PurchaseInvoiceDetail[] => {
    return tableData.value.map((item) => ({
        id: 0,
        invoiceCode: purchaseInvoices.value.code,
        goodId: item.goodId,
        quantity: item.quantity,
        invoicingQuantity: item.invoicingQuantity,
        invoicingAmount: item.invoicingAmount,
        tax: item.tax,
        notes: item.notes || '采购发票明细',
        createBy: purchaseInvoices.value.orderCreator,
        createTime: new Date().toISOString(),
        updateBy: purchaseInvoices.value.modifier,
        updateTime: new Date().toISOString(),
        warehouseId: item.storeId,
        isDelete: 0,
    }));
};

// 添加商品行
const addGoodsRow = () => {
    tableData.value.push({
        id: generateUUID(),
        goodId: 0,
        goodsCode: '',
        goodsName: '',
        warehouseName: '',
        quantity: 0,
        invoicingQuantity: 0,
        invoicingAmount: 0,
        actualPrice: 0,
        storeId: null,
        tax: 13,
        taxIncludedPrice: 0,
        notes: '',
        kname: '',
    });
};

// 定义 formRef
const formRef = ref<FormInstance>();

// 新增采购发票
const insertPurchaseInvoice = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.warning('请填写完整基本信息');
            return;
        }

        if (!sourceSheet.value) {
            ElMessage.warning('请先选择一个采购入库单');
            return;
        }

        if (tableData.value.length === 0) {
            ElMessage.warning('请至少添加一条商品明细');
            return;
        }

        // 添加对“开票数量”和“开票金额”的验证
        const hasInvalidGoods = tableData.value.some(item =>
            item.invoicingQuantity === undefined ||
            item.invoicingQuantity === null ||
            item.invoicingQuantity <= 0 ||
            item.invoicingAmount === undefined ||
            item.invoicingAmount === null ||
            item.invoicingAmount <= 0
        );
        if (hasInvalidGoods) {
            ElMessage.warning('请确保所有商品的开票数量和开票金额都已填写且大于0');
            return;
        }

        try {
            loading.value = true;
            const details = generateDetails();
            if (details.length === 0) {
                ElMessage.warning('请至少添加一条商品明细');
                return;
            }

            // 获取供应商名称
            const supplier = supplierList.value.find((s) => s.id === purchaseInvoices.value.supplierId);
            if (!supplier) {
                ElMessage.warning('供应商信息无效');
                return;
            }


            purchaseInvoices.value.amount = totalAmount.value;
            purchaseInvoices.value.originalOrderNum = sourceSheet.value;

            console.log(purchaseInvoices.value)
            console.log(details)

            const response = await request.post('/cg/purchaseInvoice/insertPurchaseInvoice', {
                purchaseInvoice: purchaseInvoices.value,
                details,
            });

            if (response.data.code === '200') {
                ElMessage.success('新增采购发票成功');
                // 重置表单
                purchaseInvoices.value = {
                    id: 0,
                    code: '',
                    codeDate: '',
                    invoiceType: InvoiceType.Normal,
                    supplierId: null,
                    invoiceNum: '',
                    codeState: CodeState.NotAudited,
                    originalOrderNum: '',
                    amount: 0,
                    orderCreationTime: new Date(),
                    orderCreator: '当前用户',
                    orderDepartment: '采购部',
                    modifyTime: new Date(),
                    modifier: '当前用户',
                };
                tableData.value = [
                    {
                        id: generateUUID(),
                        goodId: 0,
                        goodsCode: '',
                        goodsName: '',
                        warehouseName: '',
                        quantity: 0,
                        invoicingQuantity: 0,
                        invoicingAmount: 0,
                        actualPrice: 0,
                        storeId: null,
                        tax: 13,
                        taxIncludedPrice: 0,
                        notes: '',
                        kname: '',
                    },
                ];
                sourceSheet.value = '';
                await getDocCode();
                formRef.value.resetFields();
                router.push('/home/fp/cgfp');
            } else {
                ElMessage.error(response.data.msg || '新增采购发票失败');
            }
        } catch (error) {
            ElMessage.error('新增采购发票失败');
            console.error('新增失败:', error);
        } finally {
            loading.value = false;
        }
    });
};

// 仓库变化处理
const storeChange = async (row: any) => {
    try {
        const response = await request.get('/kc/StoreGoodSummary/selectKcStoreGoodBySidCid', {
            params: {
                sid: row.storeId,
                gid: row.goodId,
            }
        });
        if (response.data.data) {
            row.stock = response.data.data.stock;
            row.singleCost = response.data.data.singleCost;
        } else {
            row.stock = 0;
            row.singleCost = 0;
        }
    } catch (error) {
        console.error('获取库存数据失败:', error);
    }
};

// 初始化
onMounted(async () => {
    await Promise.all([getDocCode(), selectSupplier(), fetchData(1)]);
});
</script>

<style scoped>
.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.required-label::after {
    content: "*";
    color: #f56c6c;
    margin-left: 4px;
}

.goods-table {
    margin-top: 20px;
}

.toolbar {
    margin-bottom: 15px;
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
    text-align: center;
}

.total-summary {
    background: #fff8dc;
    padding: 12px 20px;
    display: flex;
    justify-content: flex-end;
    border: 1px solid #ebeef5;
    border-top: none;
}

.total-label {
    font-weight: 600;
    color: #606266;
    margin-right: 30px;
}

.total-amount {
    color: #f56c6c;
    min-width: 120px;
    text-align: right;
    font-family: Arial, sans-serif;
}

.pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
}

.dialog-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
    gap: 10px;
}

.date-label {
    color: #606266;
    margin: 0 10px;
}

.date-separator {
    margin: 0 8px;
    color: #c0c4cc;
}

.selected-info {
    margin: 12px 0;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #606266;
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;
}

.action-buttons {
    display: flex;
    gap: 15px;
}

:deep(.el-dialog__header) {
    border-bottom: 1px solid #ebeef5;
}
</style>
